package org.apache.bigtop.manager.stack.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.bigtop.manager.stack.common.exception.StackException;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Slf4j
public class PropertiesUtils {

    /**
     * readProperties from file
     *
     * @param fileName fileName
     * @return Map<Object, Object>
     * @throws IOException
     */
    public static Map<Object, Object> readProperties(String fileName) {
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(fileName, StandardCharsets.UTF_8));
        } catch (IOException e) {
            log.error("readProperties error,", e);
            throw new StackException(e);
        }

        return properties;
    }

    /**
     * writeProperties to file
     *
     * @param fileName  fileName
     * @param configMap configMap
     * @throws IOException
     */
    public static void writeProperties(String fileName, Map<String, Object> configMap) {
        try {
            OutputStream os = new FileOutputStream(fileName);
            for (Map.Entry<String, Object> entry : configMap.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                String s = key + "=" + value + "\n";
                os.write(s.getBytes());
            }
            os.flush();
            os.close();
        } catch (Exception e) {
            log.error("writeProperties error,", e);
        }

    }

    /**
     * writeProperties to file
     *
     * @param fileName   fileName
     * @param configList configList
     * @throws IOException
     */
    public static void writeProperties(String fileName, List<Map<String, Object>> configList) {
        //创建Properties
        Properties properties = new Properties();

        for (Map<String, Object> map : configList) {
            properties.setProperty(String.valueOf(map.get("name")), String.valueOf(map.get("value")));
        }

        log.info("writeProperties: {}", properties);
        try {
            properties.store(new FileWriter(fileName, StandardCharsets.UTF_8), "Generated by Apache BigTop Manager.");
        } catch (IOException e) {
            log.error("writeProperties error,", e);
            throw new StackException(e);
        }

    }
}
